import {
    getSystemInfoSync, makePhoneCall,
    openSetting,
    setClipboardData, setNavigationBarColor,
    setNavigationBarTitle,
    useShareAppMessage,
    login,
    getUserProfile,
} from "@tarojs/taro";
import redux from "../reduxjs";
import toast from "../toast";
import event from "../event";
import { toSearchByJson } from "../utils";



class App {
    //   info event
    private InfoEvent = 'Taro-App-Info';
    //   window event
    private WindowEvent = 'Taro-App-Window';

    private _initInfo = () => {
        const info = getSystemInfoSync();
        redux.add(this.InfoEvent, info);
        event.trigger(this.InfoEvent, info);
        return info;
    }

    /**
     * 初始化窗口高度
     */
    private _initWindow = () => {
        const info = this._initInfo();
        const width = info.windowWidth;
        const height = info.windowHeight;
        if (height === 0 || width === 0 || typeof width !== 'number' || typeof height !== 'number') {
            setTimeout(() => this._initWindow(), 10)
        } else {
            redux.add(this.WindowEvent, { width, height });
            setTimeout(() => event.trigger(this.WindowEvent, { width, height }), 10)
        }
    }

    constructor() {
    }

    init() {
        console.log('初始化 App');
        this._initInfo();
        this._initWindow();
    }

    /**
     * 获取系统信息
     */
    getInfo(): ReturnType<typeof getSystemInfoSync> {
        return redux.get(this.InfoEvent) ?? undefined;
    }

    getWindow(): { width: number, height: number } {
        return redux.get(this.WindowEvent) ?? undefined;
    }

    /**
     * 打开设置页
     */
    openToSetting() {
        return new Promise((resolve, reject) => {
            openSetting({
                withSubscriptions: true,
                success: () => {
                    resolve(true);
                },
                fail: (err) => {
                    console.warn('err', err);
                    reject(err)
                }
            }).then()
        })
    }

    /**
     * 复制文本
     * @param text
     * @param successText
     */
    copy(text: string, successText?: string) {
        setClipboardData({
            data: text,
            success: () => {
                toast.show(successText ?? '复制成功', 'success')
            },
            fail: (err) => {
                console.warn('err', err);
                toast.show('复制失败', 'error')
            }
        }).then()
    }

    /**
     * 分享按钮
     * @param title
     * @param path
     * @param params
     */
    shareButton(title: string, path: string, params?: object) {
        useShareAppMessage((res) => {
            if (res.from === 'button') {
                return {
                    title,
                    path: `${path}${params ? `?${toSearchByJson(params)}` : ''}`,
                }
            }
            return {
                title,
                path: `${path}${params ? `?${toSearchByJson(params)}` : ''}`,
            }
        })
    }

    /**
     * 分享菜单
     * @param title
     * @param path
     * @param params
     */
    shareMenu(title: string, path: string, params?: object) {
        useShareAppMessage(() => {
            return {
                title,
                path: `/${path}${params ? `?${toSearchByJson(params)}` : ''}`,
            }
        })
    }

    /**
     * 设置标题
     * @param title
     */
    setNavBarTitle(title: string) {
        setNavigationBarTitle({ title }).then()
    }

    /**
     * 设置导航栏颜色
     * @param backgroundColor
     * @param frontColor          前景色值，包括按钮、标题、状态栏的颜色，仅支持 #ffffff 和 #000000
     */
    setNavBarColor(backgroundColor: string, frontColor?: string) {
        setNavigationBarColor({
            backgroundColor,
            frontColor: frontColor ?? '#000000'
        }).then()
    }

    /**
     * 拨打电话
     * @param phoneNumber
     */
    callPhone(phoneNumber: string) {
        makePhoneCall({ phoneNumber }).then()
    }


    /**
     * 登录
     */
    logIn(): Promise<{ code: string }> {
        return new Promise((resolve, reject) => {
            login({
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            }).then()
        })
    }


    /**
     * 获取用户信息
     * @param content
     */
    getUserInfo(content?: string) {
        return new Promise((resolve, reject) => {
            getUserProfile({
                desc: content ?? '获取用户信息',
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            }).then()
        })
    }
}

export default new App();
